package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-02-27
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    //  频道管理--分页查询频道信息
    @Override
    public PageResult<ChannelDto> findByPage(ChannelDto dto) {
        //1. 设置分页条件
        IPage<AdChannel> ipage = new Page<>(dto.getPage(),dto.getSize());
        //2. 创建查询条件
        QueryWrapper<AdChannel> queryWrapper = new QueryWrapper<>();
        //2.1 当名字不为空时
        if (StringUtils.isNotBlank(dto.getName())){
            queryWrapper.like("name",dto.getName());
        }
        //3. 获取频道的分页对象
        IPage<AdChannel> adChannelIPage = page(ipage, queryWrapper);
        //4. 判断频道的分页对象是否为空，或者里面的集合是否为空
        if (adChannelIPage==null|| CollectionUtils.isEmpty(adChannelIPage.getRecords())){
            //4.1 查询结果为空时，返回null
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //5. 不为空时，将AdChannel类型转换为ChannelDto类型，并返回结果
        List<ChannelDto> channelDtos = BeanHelper.copyWithCollection(adChannelIPage.getRecords(), ChannelDto.class);
        return new PageResult<>(dto.getPage(),dto.getSize(),adChannelIPage.getTotal(),channelDtos);
    }

    //  频道管理--删除频道信息
    @Override
    public void delete(Long id) {
        AdChannel adChannel = this.getById(id);
        if(adChannel == null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(adChannel.getStatus()){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"只有在无效状态才能删除");
        }
        boolean b = this.removeById(id);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"删除失败！");
        }
    }
}
